import { useContext, useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from 'axios';
import "./register.css";
import { UserContext } from "../context/userContext";

const Register = () => {
  const [userData, setUserData] = useState({
    name: '',
    email: '',
    password: '',
    confirmPassword: ''
  });

  const [error, setError] = useState('');
  const navigate = useNavigate();
  const { currentUser, setCurrentUser } = useContext(UserContext);

  useEffect(() => {
    if (currentUser) {
      navigate('/');
    }
  }, [currentUser, navigate]);

  const changeInputHandler = (e) => {
    setUserData(prevState => {
      return { ...prevState, [e.target.name]: e.target.value };
    });
  };

  const registerUser = async (e) => {
    e.preventDefault();
    setError('');
    try {
      const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/users/register`, userData);
      const newUser = await response.data;
      console.log(newUser);

      if (!newUser) {
        setError('Failed to register user. Please try again.');
      } 
        setCurrentUser(newUser);
        navigate('/');
      
    } catch (err) {
      setError(err.response.data.message);
    }
  };

  return (
      <section className="register">
        <div className="text-group_1 flex-col justify-between">
          <span className="text_3">创建账户！</span>
          <span className="text_4">请创建账户以继续使用我们的服务</span>
        </div>

        <form className="form register__form" onSubmit={registerUser}>
          {error && <p className="form__error-message">{error}</p>}
        <div className="box_3 flex-row justify-between">
          <div className="image-wrapper_1 flex-col">
            <img
                className="label_2"
                src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNG86ee86708cf90f3b32dbbf49c123137a.png"}
            />
          </div>
          <div className="text-group_2 flex-col justify-between">
            <span className="text_5">昵称</span>
            <input className="text_8" type="text" placeholder="请输入您的昵称" name="name" value={userData.name}
                   onChange={changeInputHandler}
                   autoFocus/>
          </div>
        </div>

        <div className="box_3 flex-row justify-between">
          <div className="image-wrapper_1 flex-col">
            <img
                className="label_2"
                src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGbe33209837fd2b314332d897e7b9d0a5.png"}
            />
          </div>
          <div className="text-group_2 flex-col justify-between">
            <span className="text_5">邮箱</span>
            <input className="text_8" type="text" placeholder="请输入您的邮箱号" name="email" value={userData.email}
                   onChange={changeInputHandler}
                   autoFocus/>
          </div>
        </div>

        <div className="box_3 flex-row justify-between">
          <div className="image-wrapper_2 flex-col">
            <img
                className="label_3"
                src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGbc788a31bba3ad0c92eb3c1f40e5a172.png"}
            />
          </div>
          <div className="text-group_2 flex-col justify-between">
            <span className="text_7">密码</span>
            <input className="text_8" type="password" placeholder="请设置8-16的登录密码，支持特殊符号" name="password"
                   value={userData.password}
                   onChange={changeInputHandler}/>
          </div>
        </div>

        <div className="box_3 flex-row justify-between">
          <div className="image-wrapper_2 flex-col">
            <img
                className="label_3"
                src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGbc788a31bba3ad0c92eb3c1f40e5a172.png"}
            />
          </div>
          <div className="text-group_2 flex-col justify-between">
            <span className="text_7">请确认密码</span>
            <input className="text_8" type="password" placeholder="再次输入密码" name="confirmPassword"
                   value={userData.confirmPassword}
                   onChange={changeInputHandler}/>
          </div>
        </div>
        <div className="text-wrapper_3 flex-col">
          <button type="submit" className="text_11">创建账户</button>
        </div>
        </form>
        <span className="text_10">已有账户？<Link className="text_13" to='/login'>登录</Link></span>

      </section>
  );
};

export default Register;

